<!--
*@Author: QWP
*@Description: 派车申请
*@paramt: pType 1 派车申请        2: 派车申请审核       3 确认
*@Date 2024-07-15 09:58
-->
<template>
  <a-layout
    class="f-h-100 s-bg-white"
    id="test">
    <u-search-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <u-button-space>
            <u-icon-button @click="getSearch(1)">查询</u-icon-button>
            <template v-if="route.params.pType != '3'">
              <u-icon-button
                itype="export"
                @click="exportBtn">
                导出
              </u-icon-button>
              <u-icon-button
                itype="record"
                @click="showFlow = true"
                v-if="isReport == false">
                流程记录
              </u-icon-button>
            </template>
          </u-button-space>
        </a-col>
        <a-col flex="1">
          <a-row justify="end">
            <u-button-space>
              <template v-if="route.params.pType == 1">
                <u-icon-button
                  itype="add"
                  @click="toEdit(1)">
                  新增
                </u-icon-button>
                <u-icon-button
                  itype="edit"
                  @click="toEdit(2)">
                  修改
                </u-icon-button>
                <u-icon-button
                  itype="report"
                  @click="auditAbout('1')">
                  上报
                </u-icon-button>
                <u-icon-button
                  itype="recall"
                  @click="auditAbout('4')">
                  取回
                </u-icon-button>
                <u-icon-button
                  itype="delete"
                  @click="deleteBtn">
                  删除
                </u-icon-button>
                <!-- <u-icon-button itype="recall" @click="recallReport">撤销上报 </u-icon-button> -->
              </template>
              <template v-else-if="route.params.pType == 2">
                <u-icon-button
                  itype="audit"
                  @click="auditAbout('2')"
                  v-if="searchF.model.status != 3">
                  审核
                </u-icon-button>
                <u-icon-button
                  itype="recall"
                  @click="auditAbout('4')"
                  v-if="searchF.model.status == 3">
                  取回
                </u-icon-button>
                <u-icon-button
                  itype="close"
                  @click="auditAbout('3')"
                  v-if="searchF.model.status != 3">
                  退回
                </u-icon-button>
              </template>
              <template v-else-if="route.params.pType == 3">
                <u-icon-button @click="confirmSen">
                  <u-icon-font type="icon-cheliangguanli"></u-icon-font>
                  派车确认
                </u-icon-button>
                <u-icon-button
                  itype="delete"
                  @click="cancelConfirm">
                  取消派车
                </u-icon-button>
              </template>
            </u-button-space>
          </a-row>
        </a-col>
      </u-form>
    </u-search-header>
    <u-table-content class="f-padding-rl24">
      <u-table
        :columns="columns"
        :data="tabData"
        v-model:pagination="pagenation"
        :loading="loading"
        :scroll="{ y: useTableScroll() }"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @onDblclick="
          (record) => {
            current = record;
            dialogTitle = `${route.params.pType == 3 ? '派车确认' : '用车申请'}${formatDialogTitle(record)}`;
            showEdit = true;
          }
        "
        @change="getSearch"></u-table>
    </u-table-content>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit
    v-model:open="showEdit"
    wrap-class-name="full-modal"
    :title="dialogTitle"
    :current="current"
    @success="
      (isClose) => {
        current = {};
        showEdit = false;
        getSearch();
      }
    "
    @close="current = {}" />

  <!-- 流程记录 -->
  <u-act-flowd
    v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="send_car_info" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch, onActivated } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from "vue-router";
import { useLoginStore, useBaseStore } from "@/store";
import { storeToRefs } from "pinia";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps } from "ant-design-vue";
import { CheckCircleOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { numberC, messageC, alertC, nullC } from "@/util/common";
import { formatAmt, formatDialogTitle } from "@/util/format.ts";
import { statusA } from "@/common/model/base";
import dayjs from "dayjs";
import Edit from "./Edit.vue";
import { cloneDeep } from "lodash";
import { useTableScroll } from "@/hooks/useTable";
import { useAuditAbout, IAuditParams } from "@/hooks/useAudit";
import { usePageTypeShow, useSearchShow } from "@/hooks/useAuditEl";
import * as sendApi from "@/service/administration/sendCar";
import * as driverApi from "@/service/administration/driver";
import * as auditApi from "@/service/audit";

const props = defineProps<{
  isReport?: boolean;
}>();

const route = useRoute();
const router = useRouter();
const { userInfo } = storeToRefs(useLoginStore());
const { DISPATCH_STATUS, DISPATCH_SOURCE, APP_STATUS, ISPRINT, deptData } = storeToRefs(useBaseStore());

onMounted(() => {
  initPageStatus();
});

// 基础数据
const baseData = reactive({
  pcData: DISPATCH_STATUS.value,
  lyData: DISPATCH_SOURCE.value,
  auditData: APP_STATUS.value,
  dyData: APP_STATUS.value,
});

// 列表筛选
let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: (total) => `共 ${total} 条`,
});
const searchF = reactive({
  model: {
    keywords: null,
    status: "1",
    assignStatus: "",
    dispatchstatus: "",
    dispatchsource: "",
  },
});

const formItemProps: FormItemProps = {
  labelWidth: "80px",
  wrapperCol: { span: 16 },
};

// 报表额外查询
const searchEl: Array<_IFormEl> = reactive([
  {
    label: "用车部门",
    key: "vehicledeptid",
    element: "select",
    col: { span: 4 },
    hide: props.isReport != true,
    formItemProps: formItemProps,
    componentProps: { options: deptData.value },
  },
  {
    label: "数据状态",
    key: "status",
    element: "select",
    hide: props.isReport == true,
    col: { span: route.params.pType == "3" ? 0 : 4 },
    formItemProps: formItemProps,
    componentProps: {
      options: computed(() => statusA(route.params.pType) ?? []),
      allowClear: route.params.pType == "2" ? false : true,
    },
  },
  {
    label: "派车状态",
    key: "assignStatus",
    element: "select",
    col: { span: route.params.pType == "3" ? 4 : 0 },
    formItemProps: formItemProps,
    componentProps: {
      options: [
        { label: "未派车", value: "0" },
        { label: "已派车", value: "1" },
      ],
      allowClear: true,
    },
  },
  {
    label: "关键字",
    key: "keywords",
    element: "input",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: {
      placeholder: "车牌号、申请人",
    },
  },
]);

const showFlow = ref(false);

// 列表
const loading = ref<boolean>(false);
const tabSelData = ref<any[]>([]);
const tabData = ref<any[]>([]);
let originCol: Array<TableColumnProps> = reactive([
  { dataIndex: "index", title: "序号", width: 50, align: "center", customRender: ({ index }) => (index += 1) },
  // { dataIndex: "statuss", title: "数据状态", width: 100, align: 'center' },
  { dataIndex: "applicant", title: "申请人", width: 150, align: "center" },
  { dataIndex: "applicantphone", title: "申请人电话", width: 150, align: "center" },
  { dataIndex: "vehicledeptname", title: "用车部门", width: 150, align: "center" },
  { dataIndex: "passengernumber", title: "用车人数", width: 150, align: "right" },
  { dataIndex: "vehclescope", title: "用车范围", width: 150, align: "center" },
  {
    dataIndex: "fkdrivername",
    title: "驾驶员",
    width: 150,
    align: "center",
    customRender: ({ text }) => (text == "null" ? "" : nullC(text)),
  },
  {
    dataIndex: "fkvehiclenumber",
    title: "车牌号",
    width: 150,
    align: "center",
    customRender: ({ text }) => (text == "null" ? "" : nullC(text)),
  },
  { dataIndex: "vehicleusername", title: "用车人", width: 150, align: "center" },
  { dataIndex: "vehicleuserphone", title: "用车人电话", width: 150, align: "center" },
  { dataIndex: "reason", title: "用车事由", width: 200 },
]);
let columns: Array<TableColumnProps> = reactive([]);

// 列表查询
const getSearch = async (current) => {
  if (current == 1) {
    pagenation.current = current;
  }
  // 派车确认
  if (route.params.pType == 3) {
    searchF.model.status = 3;
  }
  loading.value = true;
  try {
    searchF.current = pagenation.current;
    searchF.size = pagenation.pageSize;
    const data = await sendApi.page(searchF);
    if (data.code == 0) {
      tabData.value = data.data.records;
      pagenation.total = data.data.total;
    }
  } catch (error) {}
  loading.value = false;
};

// 初始化页面数据
const initPageStatus = () => {
  const pageStatus = { 1: "1", 2: "2" };
  searchF.model.pageStatus = nullC(pageStatus[route.params.pType]);
  const cols = cloneDeep(originCol);
  searchF.model.assignStatus = "";
  if (["1", "2"].includes(route.params.pType + "")) {
    cols.push({ dataIndex: "statuss", title: "审核状态", width: 110, align: "center", fixed: "right" });
  }
  // 派车确认
  else if (route.params.pType == 3) {
    searchF.model.assignStatus = "0";
    cols.push({ dataIndex: "assignStatuss", title: "派车状态", width: 110, align: "center", fixed: "right" });
  }

  const status = { 1: "1", 2: "2", 3: "3" };
  searchF.model.status = nullC(status[route.params.pType]);

  // 报表页面直接查询审核完成的数据
  if (props.isReport == true) {
    searchF.model.status = "3";
  }
  columns.splice(0, columns.length, ...cols);
  getSearch();
};

onActivated(() => {
  initPageStatus();
});

// 获取枚举
const getEnum = async () => {
  try {
    const data = await driverApi.getselectPlateNumber();
    if (data.code == 0) {
      baseData.cphData = data.data; // platenumber
    }
  } catch (error) {}
};

// 编辑
const current = ref<object>({});
const backParams = ref<object>({});
const keyid = ref<string>("");
let dialogTitle = ref<string>("用车申请编辑");
let showEdit = ref<boolean>(false);
// type 1 新增   2 修改    3 单条审核
const toEdit = (type: number) => {
  if (type == 1) {
    keyid.value = "";
    dialogTitle.value = "用车申请编辑";
  } else if (type == 2) {
    if (tabSelData.value.length !== 1) {
      alertC("能且只能选择一条数据", "warning");
      return;
    }
    if (!["1", "4"].includes(tabSelData.value[0]["status"] + "")) {
      alertC("只能修改未提交和已退回的数据", "warning");
      return;
    }
    dialogTitle.value = "用车申请" + formatDialogTitle(tabSelData.value[0]);
    keyid.value = tabSelData.value[0].keyid;
    current.value = tabSelData.value[0];
  }
  showEdit.value = true;
};

// 删除
const deleteBtn = () => {
  if (tabSelData.value.length == 0) {
    messageC("请先选择要删除的数据!", "warning");
    return;
  }

  let noDel = tabSelData.value.some((i) => ["2", "3"].includes(i["status"] + ""));
  if (noDel) {
    messageC("审核中或审核完成的数据不能删除!");
    return;
  }

  alertC("确定删除选中的数据?", "confirm").then(async () => {
    let ids = tabSelData.value.map((item) => item.keyid);
    loading.value = true;
    try {
      const data = await sendApi.del({ ids: ids.join(",") });
      if (data.code == 0) {
        getSearch();
        messageC(data.msg, "success");
      } else {
        alertC(data.msg, "warning");
      }
    } catch (error) {}
    loading.value = false;
  });
};

// 上报、审核、退回
const auditAbout = async (type: string) => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: "send_car_info",
    selDatas: tabSelData.value,
  };
  try {
    const res = await useAuditAbout(type, auditParams);
    if (res) {
      pagenation.current = 1;
      getSearch();
    }
  } catch (error) {}
  loading.value = false;
};

// 派车确认
const confirmSen = () => {
  if (tabSelData.value.length != 1) {
    messageC("请选择一条数据进行操作！");
    return;
  }

  dialogTitle.value = "派车确认";
  current.value = tabSelData.value[0];
  showEdit.value = true;
};

// 取消派车
const cancelConfirm = async () => {
  if (tabSelData.value.length == 0) {
    messageC("请先选择需要操作的数据！");
    return;
  }

  let noCancel = tabSelData.value.some((i) => i["assignStatuss"] != "已派车");
  if (noCancel) {
    messageC("请选择已派车的数据进行取消！");
    return;
  }

  loading.value = true;
  try {
    await alertC("确认对选中的数据进行取消派车？", "confirm");
    let ids = tabSelData.value.map((i) => i.keyid);
    const res = await sendApi.detialDel({ ids: ids.join(",") });
    if (res.code == 0) {
      messageC(res.msg, "success");
      getSearch();
    } else {
      messageC(res.msg);
    }
  } catch (error) {}
  loading.value = false;
};

// 导出
const exportBtn = async () => {
  loading.value = true;
  try {
    const res = await sendApi.download({ ...searchF, size: -1 });
  } catch (error) {}
  loading.value = false;
};

defineExpose({
  toEdit,
});
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
